package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * OI类
 * 实现对象标识符数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class OI implements AxdrType {
    private byte[] value = new byte[2]; // 2字节对象标识符
    private byte[] dataCode = null;

    public OI() {
    }

    public OI(byte[] value) {
        if (value.length != 2) {
            throw new IllegalArgumentException("OI value must be 2 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 2);
    }

    public byte[] getValue() {
        return value;
    }

    public void setValue(byte[] value) {
        if (value.length != 2) {
            throw new IllegalArgumentException("OI value must be 2 bytes");
        }
        System.arraycopy(value, 0, this.value, 0, 2);
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码2个字节的对象标识符
        this.value[0] = (byte) input.read();
        this.value[1] = (byte) input.read();
        return 2;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码2个字节的对象标识符
        try {
            output.write(this.value[0]);
            output.write(this.value[1]);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 2;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return String.format("OI[%02X%02X]",
                this.value[0] & 0xFF,
                this.value[1] & 0xFF);
    }
}